package com.reservation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.reservation.common.BusinessException;
import com.reservation.entity.Exhibition;
import com.reservation.entity.ExhibitionReservation;
import com.reservation.mapper.ExhibitionMapper;
import com.reservation.mapper.ExhibitionReservationMapper;
import com.reservation.service.ExhibitionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 展览服务实现类
 */
@Service
public class ExhibitionServiceImpl implements ExhibitionService {

    @Autowired
    private ExhibitionMapper exhibitionMapper;
    
    @Autowired
    private ExhibitionReservationMapper exhibitionReservationMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Exhibition addExhibition(Exhibition exhibition) {
        // 设置创建时间和更新时间
        exhibition.setCreateTime(LocalDateTime.now());
        exhibition.setUpdateTime(LocalDateTime.now());
        
        // 设置展览状态
        LocalDate now = LocalDate.now();
        if (exhibition.getStartDate().isAfter(now)) {
            exhibition.setStatus("NOT_STARTED");
        } else if (exhibition.getEndDate().isBefore(now)) {
            exhibition.setStatus("ENDED");
        } else {
            exhibition.setStatus("IN_PROGRESS");
        }
        
        // 保存展览信息
        exhibitionMapper.insert(exhibition);
        
        return exhibition;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Exhibition updateExhibition(Exhibition exhibition) {
        // 检查展览是否存在
        Exhibition existExhibition = exhibitionMapper.selectById(exhibition.getId());
        if (existExhibition == null) {
            throw new BusinessException("展览不存在");
        }
        
        // 设置更新时间
        exhibition.setUpdateTime(LocalDateTime.now());
        
        // 更新展览状态
        LocalDate now = LocalDate.now();
        if (exhibition.getStartDate() != null && exhibition.getEndDate() != null) {
            if (exhibition.getStartDate().isAfter(now)) {
                exhibition.setStatus("NOT_STARTED");
            } else if (exhibition.getEndDate().isBefore(now)) {
                exhibition.setStatus("ENDED");
            } else {
                exhibition.setStatus("IN_PROGRESS");
            }
        }
        
        // 更新展览信息
        exhibitionMapper.updateById(exhibition);
        
        // 返回更新后的展览信息
        return exhibitionMapper.selectById(exhibition.getId());
    }

    @Override
    public Exhibition getExhibitionById(Long id) {
        Exhibition exhibition = exhibitionMapper.selectById(id);
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }
        return exhibition;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteExhibition(Long id) {
        // 检查展览是否存在
        Exhibition exhibition = exhibitionMapper.selectById(id);
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }
        
        // 删除展览
        return exhibitionMapper.deleteById(id) > 0;
    }

    @Override
    public IPage<Exhibition> getExhibitionList(Page<Exhibition> page, String name, String status, String location) {
        LambdaQueryWrapper<Exhibition> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.isNotBlank(name)) {
            queryWrapper.like(Exhibition::getName, name);
        }
        if (StringUtils.isNotBlank(status)) {
            queryWrapper.eq(Exhibition::getStatus, status);
        }
        if (StringUtils.isNotBlank(location)) {
            queryWrapper.like(Exhibition::getLocation, location);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Exhibition::getCreateTime);
        
        // 执行查询
        return exhibitionMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Exhibition> getAllExhibitions() {
        LambdaQueryWrapper<Exhibition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Exhibition::getCreateTime);
        return exhibitionMapper.selectList(queryWrapper);
    }

    @Override
    public List<Exhibition> getOngoingExhibitions() {
        LambdaQueryWrapper<Exhibition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Exhibition::getStatus, "IN_PROGRESS");
        queryWrapper.orderByDesc(Exhibition::getCreateTime);
        return exhibitionMapper.selectList(queryWrapper);
    }

    @Override
    public List<Exhibition> getUpcomingExhibitions() {
        LambdaQueryWrapper<Exhibition> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Exhibition::getStatus, "NOT_STARTED");
        queryWrapper.orderByAsc(Exhibition::getStartDate);
        return exhibitionMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Exhibition updateExhibitionStatus(Long id, String status) {
        // 检查展览是否存在
        Exhibition exhibition = exhibitionMapper.selectById(id);
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }
        
        // 更新状态
        Exhibition updateExhibition = new Exhibition();
        updateExhibition.setId(id);
        updateExhibition.setStatus(status);
        updateExhibition.setUpdateTime(LocalDateTime.now());
        exhibitionMapper.updateById(updateExhibition);
        
        // 返回更新后的展览信息
        return exhibitionMapper.selectById(id);
    }

    @Override
    public boolean checkDateAvailable(Long exhibitionId, LocalDate date) {
        // 检查展览是否存在
        Exhibition exhibition = exhibitionMapper.selectById(exhibitionId);
        if (exhibition == null) {
            throw new BusinessException("展览不存在");
        }
        
        // 检查日期是否在展览时间范围内
        if (date.isBefore(exhibition.getStartDate()) || date.isAfter(exhibition.getEndDate())) {
            return false;
        }
        
        // 检查当天预约人数是否已满
        int count = getReservationCount(exhibitionId, date);
        return count < exhibition.getDailyLimit();
    }

    @Override
    public int getReservationCount(Long exhibitionId, LocalDate date) {
        LambdaQueryWrapper<ExhibitionReservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ExhibitionReservation::getExhibitionId, exhibitionId);
        queryWrapper.eq(ExhibitionReservation::getReservationDate, date);
        queryWrapper.in(ExhibitionReservation::getStatus, "PENDING", "APPROVED");
        
        // 查询预约记录
        List<ExhibitionReservation> reservations = exhibitionReservationMapper.selectList(queryWrapper);
        
        // 计算总预约人数
        return reservations.stream().mapToInt(ExhibitionReservation::getVisitorCount).sum();
    }
}